<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { post } from '@/api/request'
import SearchForm from '@/components/business/SearchForm.vue'

// 搜索配置
const searchData = ref([
  { label: '订单号', module: 'orderNo', type: 'input' },
  { label: '用户名', module: 'userName', type: 'input' },
  { label: '状态', module: 'status', type: 'select', options: [] },
  { label: '餐别', module: 'mealType', type: 'select', options: [
    { label: '早餐', value: '早餐' }, 
    { label: '午餐', value: '午餐' }, 
    { label: '晚餐', value: '晚餐' }
  ]},
  { label: '菜单日期', module: 'menuDate', type: 'date', format: 'YYYY-MM-DD' }
])

const orderList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const router = useRouter()
const ruleForm = ref({})

// 获取状态字典
async function getStatusDict() {
  try {
    const res = await post('/api/order/statusDict', {})
    if (res.code === 200) {
      const statusOptions = Object.entries(res.data).map(([value, label]) => ({
        label,
        value
      }))
      searchData.value[2].options = statusOptions
    }
  } catch (error) {
    console.error('获取状态字典失败:', error)
  }
}

// 获取订单列表
async function fetchOrders() {
  const params = {
    page: currentPage.value,
    size: pageSize.value,
    ...ruleForm.value
  }
  try {
    const res = await post('/api/order/page', params)
    console.log('API响应:', res)
    if (res.code === 200) {
      orderList.value = res.data.content || []
      total.value = res.data.total || 0
      console.log('订单列表数据:', orderList.value)
    } else {
      ElMessage.error(res.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表错误:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 搜索
function handleSearchBtn(form) {
  ruleForm.value = { ...form }
  currentPage.value = 1
  fetchOrders()
}

// 重置
function handleResetFetch() {
  ruleForm.value = {}
  currentPage.value = 1
  fetchOrders()
}

// 分页
function handlePageChange(page) {
  currentPage.value = page
  fetchOrders()
}

function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

// 查看明细
function handleDetail(row) {
  router.push({ name: 'OrderDetail', params: { id: row.id } })
}

// 退款操作
function handleRefund(row) {
  ElMessageBox.confirm('确认要退款吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        const res = await post(`/api/order/refund/${row.orderNo}`, {})
        if (res.code === 200) {
          ElMessage.success('退款成功')
          fetchOrders()
        } else {
          ElMessage.error(res.message || '退款失败')
        }
      } catch (error) {
        console.error('退款错误:', error)
        ElMessage.error('退款失败')
      }
    })
}

onMounted(async () => {
  await getStatusDict()
  await fetchOrders()
})
</script>

<template>
  <div class="container">
    <el-card shadow="never" class="order-card no-border">
      <div class="order-header">
        <span class="order-title">订单列表</span>
      </div>
      
      <!-- 搜索表单 -->
      <SearchForm :searchData="searchData" @searchFetch="handleSearchBtn" @resetFetch="handleResetFetch" />
      
      <!-- 订单表格 -->
      <el-table :data="orderList" row-key="id" style="width: 100%; margin-top: 16px;" class="no-table-border" :header-cell-style="{ background: '#f5f7fa', color: '#606266'}">
        <el-table-column prop="orderNo" label="订单号" min-width="140" />
        <el-table-column prop="userName" label="用户" min-width="100" />
        <el-table-column prop="orderDate" label="下单时间" min-width="140" />
        <el-table-column prop="menuDate" label="菜单日期" min-width="120" />
        <el-table-column prop="mealType" label="餐别" min-width="100" />
        <el-table-column prop="totalAmount" label="金额" min-width="100" />
        <el-table-column prop="statusText" label="状态" min-width="80" />
        <el-table-column label="操作" min-width="160">
          <template #default="{ row }">
            <el-button size="small" @click="handleDetail(row)">查看</el-button>
            <el-button size="small" type="danger" v-if="row.status === 'PAID'" @click="handleRefund(row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页器 -->
      <el-pagination 
        style="margin-top: 16px; text-align: right;justify-content: flex-end;" 
        background
        layout="total, sizes, prev, pager, next, jumper" 
        :total="total" 
        :page-size="pageSize"
        v-model:current-page="currentPage" 
        :page-sizes="[10, 20, 50]" 
        @update:current-page="handlePageChange"
        @update:page-size="handleSizeChange"
        :hide-on-single-page="false"
      />
    </el-card>
  </div>
</template>

<style scoped>
.order-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.order-title {
  font-size: 20px;
  font-weight: bold;
}

.no-border {
  border: none !important;
  box-shadow: none !important;
}

.no-table-border .el-table__inner-wrapper,
.no-table-border .el-table__body,
.no-table-border .el-table__header {
  border: none !important;
}

.no-table-border .el-table__cell {
  border-bottom: none !important;
}
</style>